<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="仓库编号" prop="storehouseNo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.storehouseNo"-->
      <!--          placeholder="请输入仓库编号"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="仓库名称" prop="storehouseName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.storehouseName"-->
      <!--          placeholder="请输入仓库名称"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="库区编号" prop="storehouseAreaNo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.storehouseAreaNo"-->
      <!--          placeholder="请输入库区编号"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="库区名称" prop="storehouseAreaName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.storehouseAreaName"-->
      <!--          placeholder="请输入库区名称"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="库位编号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入库位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入库位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="storehouseName">
        <el-input
          v-model="queryParams.storehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="工作中心编号" prop="workCenterNo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.workCenterNo"-->
      <!--          placeholder="请输入工作中心编号"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="工作中心名称" prop="workCenterName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.workCenterName"-->
      <!--          placeholder="请输入工作中心名称"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="外部编号" prop="outerNo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.outerNo"-->
      <!--          placeholder="请输入外部编号"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="排序" prop="sort">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.sort"-->
      <!--          placeholder="请输入排序"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="是否默认" prop="isDefault">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.isDefault"-->
      <!--          placeholder="请输入是否默认"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="库位码前缀" prop="prefix">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.prefix"-->
      <!--          placeholder="请输入库位码前缀"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:location:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:location:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:location:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['basic:location:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:location:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="single"
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
          v-hasPermi="['basic:location:print']"
        >打印二维码</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="ID" align="center" prop="id" />-->
      <af-table-column label="库位编号" align="center" prop="no" width="100" show-overflow-tooltip/>
      <af-table-column label="库位名称" align="center" prop="name" />
      <el-table-column label="库位类型" align="center" prop="locationType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.location_type" :value="scope.row.locationType"/>
        </template>
      </el-table-column>
      <af-table-column label="库区编号" align="center" prop="storehouseAreaNo" />
      <af-table-column label="库区名称" align="center" prop="storehouseAreaName" />
      <af-table-column label="仓库编号" align="center" prop="storehouseNo" />
      <af-table-column label="仓库名称" align="center" prop="storehouseName" />

      <!--      <el-table-column label="工作中心编号" align="center" prop="workCenterNo" />-->
      <!--      <el-table-column label="工作中心名称" align="center" prop="workCenterName" />-->
      <!--      <el-table-column label="状态" align="center" prop="status" />-->
      <!--      <el-table-column label="外部编号" align="center" prop="outerNo" />-->
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <!--      <el-table-column label="排序" align="center" prop="sort" />-->
      <!--      <el-table-column label="是否默认" align="center" prop="isDefault" />-->
      <!--      <el-table-column label="库位码前缀" align="center" prop="prefix" />-->
      <el-table-column label="创建人" align="center" prop="createBy" min-width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="152"/>
      <el-table-column label="最后更新人" align="center" prop="updateBy" min-width="100"/>
      <el-table-column label="最后更新时间" align="center" prop="updateTime" width="152"/>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--            v-hasPermi="['system:location:edit']"-->
      <!--          >修改</el-button>-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['system:location:remove']"-->
      <!--          >删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库位对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="仓库编号" prop="storehouseNo">-->
        <!--          <el-input v-model="form.storehouseNo" placeholder="请输入仓库编号" />-->
        <!--        </el-form-item>-->
        <el-form-item label="库位编号" prop="no">
          <el-input v-model="form.no" placeholder="请输入库位编号" :disabled="!!form.id"/>
        </el-form-item>
        <el-form-item label="库位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="库位类型" prop="locationType">
          <el-select style="width:100%;" v-model="form.locationType" filterable placeholder="请选择线边仓">
            <el-option
              v-for="dict in dict.type.location_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="storehouseNo">
          <!--          <el-input v-model="form.storehouseName" placeholder="请选择仓库" />-->
          <el-select style="width:100%;" v-model="form.storehouseNo" filterable placeholder="请选择仓库">
            <el-option
              v-for="dict in storehouseList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
              @click.native="changeStorehouse(dict, true)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区" prop="storehouseAreaNo">
          <!--          <el-input v-model="form.storehouseAreaNo" placeholder="请先选择仓库" />-->
          <el-select style="width:100%;" v-model="form.storehouseAreaNo"
                     no-data-text="请先选择仓库" filterable placeholder="请选择库区">
            <el-option
              v-for="dict in this.areaList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
              @click.native="form.storehouseAreaName = dict.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="库区名称" prop="storehouseAreaName">-->
        <!--          <el-input v-model="form.storehouseAreaName" placeholder="请输入库区名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="工作中心编号" prop="workCenterNo">-->
        <!--          <el-input v-model="form.workCenterNo" placeholder="请输入工作中心编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="工作中心名称" prop="workCenterName">-->
        <!--          <el-input v-model="form.workCenterName" placeholder="请输入工作中心名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="外部编号" prop="outerNo">-->
        <!--          <el-input v-model="form.outerNo" placeholder="请输入外部编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备注" prop="remark">-->
        <!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="是否删除：1是 0否" prop="delFlag">-->
        <!--          <el-input v-model="form.delFlag" placeholder="请输入是否删除：1是 0否" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="排序" prop="sort">-->
        <!--          <el-input v-model="form.sort" placeholder="请输入排序" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="是否默认" prop="isDefault">-->
        <!--          <el-input v-model="form.isDefault" placeholder="请输入是否默认" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="库位码前缀" prop="prefix">-->
        <!--          <el-input v-model="form.prefix" placeholder="请输入库位码前缀" />-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打印二维码对话框 -->
    <el-dialog :title="print.title" v-if="print.open" :visible.sync="print.open" width="400px" append-to-body>
      <div id='printBill' class="flex-column">
        <!-- 二维码 -->
        <div ref="qrCode"></div>
        <div style="width:360px;padding-top:6px;text-align:center">{{selection&&selection[0]?selection[0].no:''}}</div>
        <!-- 条码 -->
        <!-- <img id="barcode">
        <div style="width:360px;padding-top:6px;text-align:center">{{selection&&selection[0]?selection[0].no:''}}</div> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPrint">确 定</el-button>
        <el-button @click="print.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import JsBarcode from 'jsbarcode';
import printJS from 'print-js'

import { listLocation, getLocation, delLocation, addLocation, updateLocation } from "@/api/basic/location";
import { listArea } from "@/api/basic/area";
import { listStorehouse } from "@/api/basic/storehouse";
import { getToken } from "@/utils/auth";

export default {
  name: "Location",
  dicts: ['location_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      selection:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库位表格数据
      locationList: [],
      // 弹出层标题
      title: "",
      //库区列表
      areaMap: new Map(),
      storehouseList: [],
      areaList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storehouseNo: null,
        storehouseName: null,
        storehouseAreaNo: null,
        storehouseAreaName: null,
        no: null,
        name: null,
        workCenterNo: null,
        workCenterName: null,
        status: null,
        outerNo: null,
        sort: null,
        isDefault: null,
        prefix: null
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basic/location/importExcel"
      },
      // 打印参数
      print: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storehouseNo: [
          { required: true, message: "仓库编号不能为空", trigger: "change" }
        ],
        storehouseName: [
          { required: true, message: "仓库名称不能为空", trigger: "change" }
        ],
        storehouseAreaNo: [
          { required: true, message: "库区编号不能为空", trigger: "change" }
        ],
        storehouseAreaName: [
          { required: true, message: "库区名称不能为空", trigger: "change" }
        ],
        locationType: [
          { required: true, message: "库位类型不能为空", trigger: "change" }
        ],
        no: [
          { required: true, message: "库位编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "库位名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getStorehouseList();
  },
  methods: {
    // 打印 弹窗
    handlePrint(){
      this.print.title = "打印二维码";
      this.print.open = true;
      this.$nextTick(()=>{
        // JsBarcode('#barcode', this.selection[0].no, {
        //     format: 'CODE128', // 条形码的格式
        //     // width: 1, // 线宽
        //     height: '100px', // 条码高度
        //     lineColor: '#000', // 线条颜色
        //     displayValue: true, // 是否显示文字
        //     margin: 2// 设置条形码周围的空白区域
        // });
        var qrcode = new QRCode(this.$refs.qrCode, {
          text: this.selection[0].no, // 需要转换为二维码的内容
          width: 150,
          height: 150,
          // colorDark: '#000000',
          // colorLight: '#ffffff',
          // correctLevel: QRCode.CorrectLevel.H
        })
      })
    },
    submitPrint(){
      const style = '@page {margin:0 10mm};'//打印时去掉眉页眉尾
      //打印为什么要去掉眉页眉尾？因为眉页title时打印当前页面的title，相当于是获取html中title标签里面的内容，但是比如我打印的内容只是一个弹框里面的内容，是没有title的，这时候就会出现undefined，为了避免出现这种情况，就可以隐藏眉页眉尾
      printJS({
        printable: 'printBill',// 标签元素id
        type: 'html',
        header: '',
        targetStyles: ['*'],
        style
      });
    },
    /** 查询库位列表 */
    getList() {
      this.loading = true;
      listLocation(this.queryParams).then(response => {
        this.locationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storehouseNo: null,
        storehouseName: null,
        storehouseAreaNo: null,
        storehouseAreaName: null,
        no: null,
        name: null,
        workCenterNo: null,
        workCenterName: null,
        status: "0",
        outerNo: null,
        remark: null,
        delFlag: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        sort: null,
        isDefault: null,
        prefix: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selection = selection
      this.nos = selection.map(item => item.no)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.areaList = [];
      this.open = true;
      this.title = "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLocation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库位";
        let key = {no:this.form.storehouseNo, name:this.form.storehouseName};
        this.changeStorehouse(key,false);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLocation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const nos = row.no || this.nos;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delLocation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/location/export', {
        ...this.queryParams, ids: this.ids
      }, `库位管理_${new Date().getTime()}.xlsx`)
    },
    /** 获取仓库列表 */
    getStorehouseList(){
      listStorehouse().then(response => {
        this.storehouseList = response.rows;
      });
    },
    /** 获取库区列表 */
    getAreaList(storehouseNo){
      listArea({storehouseNo:storehouseNo}).then(response => {
        this.areaList = response.rows;
      });
    },
    //仓库变更连带处理
    changeStorehouse(dict, isInitArea){
      //处理仓库列表
      this.form.storehouseNo = dict.no;
      this.form.storehouseName = dict.name;
      if(isInitArea === true) {
        //库区置空
        this.form.storehouseAreaNo = null;
        this.form.storehouseAreaName = null;
      }
      this.getAreaList(dict.no);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "库位导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('basic/location/importTemplate', {
      }, `库位模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
